package ru.dusniz.notifypeople.users;

import org.apache.tomcat.util.json.JSONParser;
import org.apache.tomcat.util.json.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;
    public List<User> listAllClient() { return userRepository.findAll(); }

    public boolean saveUser(User user) {
        String userEmail = user.getEmail();
        String userNickname = user.getNickname();
        boolean isEqualNickname = false;
        boolean isEqualEmail = false;

        try {
            if (userRepository.findByEmail(userEmail) != null)
                isEqualEmail = true;
        } catch (Exception ignored) { }

        try {
            if (userRepository.findByNickname(userNickname) != null)
                isEqualNickname = true;
        } catch (Exception ignored) { }

        if (!isEqualEmail && !isEqualNickname) {
            userRepository.save(user);
            return true;
        } else
            return false;
    }

    public User getUser(String id) { return userRepository.findById(id).get(); }

    public void deleteUser(String id) {
        userRepository.deleteById(id);
    }


    public User parseUserObj(String jsonString) throws ParseException {
        JSONParser jsonParser = new JSONParser(jsonString);
        var data = jsonParser.object();
        return new User((String) data.get("email"),(String) data.get("nickname"),
                        (String) data.get("firstname"), (String) data.get("lastname"),
                        String.valueOf(data.get("password").hashCode()));
    }
}
